var express = require('express');
var router = express.Router();
var app = express();
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
var ObjectID = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient,
  test = require('assert');



router.get('/', function (req, res) {
  console.log("done")
  res.render('index');
});


//主页
router.route("/index").get(function (req, res, next) {
  res.render("index");
}).post(function (req, res) {
  var uname = req.body.uname;//获取前端输入的用户名
  var upwd = req.body.upwd;//获取前端输入的密码
  // 数据库操作
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('users');//连接表
    collection.findOne({ no: uname }, function (err, doc) {//查找
      if (err) {
        console.log(err);
      } else if (!doc) {//判断输入
        req.session.error1 = '用户名不存在';
        console.log("no id");
        res.send(400);
        return;
      } else {
        if (upwd != doc.password) {
          req.session.error2 = "密码错误";
          console.log("wrong password");
          res.send(400);
          return;
        } else {//判断输入，依据查到的who值判断属于哪类用户
          if (doc.who == "admin") {
            req.session.user = doc;
            console.log("done");
            res.send('iamadmin');
          } else if (doc.who == "teacher") {
            req.session.user = doc;
            console.log("done");
            res.send('iamteacher')
          } else if (doc.who == "student") {
            req.session.user = doc;
            console.log("done");
            res.send('iamstudent')
          } else {
            console.log("error")
          }
        };
      };
      db.close();
    });
  });
});


//管理员页面
router.get("/admin", function (req, res) {
  if (req.session.user.who != "admin") {
    console.log("wrong")//阻止登录
    res.render("index")//返回主页
  } else {
    //用户对应，进入相应页面
    MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
      var collection = db.collection('users');//连接表
      collection.find({ who: "teacher" }, { sort: { "no": 1 } }).toArray(function (err, doc) {//查找teacher用于列表显示
        global.tealist = doc;//定义全局变量方便调用
        res.render("admin", {
          teacherlist: doc,
        });//跳转并传值
      })
      db.close();
    });
  }
})



//管理员页面下的教师录入
router.route("/log1").get(function (req, res, next) {
  console.log("录入")
  res.render('admin', {
    teacherlist: tealist//使用全局变量tealist
  })//录入后刷新
}).post(function (req, res) {
  var tname = req.body.tname;//获取输入名
  var tpwd = req.body.tpwd;//获取输入密码
  var tid = req.body.tid;//获取id
  var sel = req.body.sel//获取系别
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('users');//连接表
    var data = {
      "name": tname,
      "password": tpwd,
      "no": tid,
      "who": "teacher",
      "department": sel
    }//定义数据库字段并赋值
    collection.insert(data, function (err, result) {//写入数据库
      if (err) {
        console.log("insert wrong")
      } else {
        console.log(result)
      }
    })
    db.close();
  });
})




//管理员页面下的删除
router.route("/del1").get(function (req, res, next) {
  console.log("删除")
  res.render('admin', {
    teacherlist: tealist
  })
}).post(function (req, res) {
  var tid = req.body.tid;
  // console.log(tid)
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {
    var collection = db.collection('users');
    var data = {
      "no": tid
    }
    collection.remove(data, function (err, result) {
      if (err) {
        console.log("delete wrong")
      } else {
        console.log(result)
      }
    })
    db.close();
  });
})






//分班页面
router.get('/class', function (req, res) {
  if (req.session.user.who != "teacher") {
    console.log("wrong")//阻止登录
    res.render("index")
  } else {
    //用户对应，进入相应页面
    var belong = req.session.user.name
    MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
      var collection = db.collection('users');//连接表
      collection.find({ who: "student", class: "1", belong: belong, course: "mongodb" }, { sort: { "no": 1 } }).toArray(function (err, doc) {
        //查询默认一班
        global.stulist1 = doc;
        res.render("class", {
          studentlist: doc,
        });//跳转到页面并传值
      })
      db.close();
    });
  }
});



//因为某些原因，在选择班级并查询后需要跳转页面
router.get("/class1", function (req, res) {
  var seld1 = req.query.sel1
  var seld2 = req.query.sel2//获取前端下拉列表的选择
  global.seld1 = seld1
  global.seld2 = seld2//定义全局变量
});


router.get("/getteaup", function (req, res) {
  var seld1 = req.query.sel1;//获取前端下拉列表的选择
  var seld2 = req.query.sel2;
  var seld3 = req.query.sel3;
  global.seld1 = seld1
  global.seld2 = seld2
  global.seld3 = seld3
  console.log("输出实验选择" + seld1 + seld2 + seld3)
});



//学生列表表格
router.get("/studentlist", function (req, res) {
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('users');//连接表
    collection.find({ who: "student", class: seld2, course: seld1 }, { sort: { "no": 1 } }).toArray(function (err, doc) {//查询所有学生用以显示
      global.stulist = doc//定义全局变量
      res.render("class", {
        studentlist: doc,
      });//跳转到class并传值，此处导致一个bug，跳转后下拉选择还是默认一班，不会变
    })
    db.close();
  });
});





//学生页面
router.get("/student", function (req, res) {
  if (req.session.user.who != "student") {
    console.log("wrong")//阻止登录
    res.render("index")//返回主页
  } else {
    //用户对应，进入相应页面
    var belong = req.session.user.belong
    MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
      var collection = db.collection('teacherup');//连接表
      collection.find({ course: "mongodb", class: "1", who: belong }).toArray(function (err, doc) {
        console.log("开始查询教师布置")
        res.render("student", {
          teauplist: doc
        });
      })
      db.close();
    });
  }
});




//教师页面
router.get("/teacher", function (req, res) {
  if (req.session.user.who != "teacher") {
    console.log("wrong")//阻止登录
    res.render("index")
  } else {
    var name = req.session.user.name
    MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
      var collection = db.collection('teacherup');//连接表
      collection.find({ course: "mongodb", class: "1", week: "w1", towho: name }).toArray(function (err, doc) {
        console.log("开始查询教师上传")
        console.log(doc)
        res.render("teacher", {
          stuuplist: doc,
        });//跳转到页面并传值
      })
      db.close();
    });
  }
});



router.get("/studentup", function (req, res) {
  var name = req.session.user.name
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('teacherup');//连接表
    collection.find({ course: seld1, class: seld2, week: seld3, towho: name }).toArray(function (err, doc) {
      console.log("开始查询教师上传123123123")
      console.log(doc)
      res.render("teacher", {
        stuuplist: doc,
      });//跳转到页面并传值
    })
    db.close();
  });
})



router.get("/teacherup", function (req, res) {
  var name = req.session.user.name
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('teacherup');//连接表
    collection.find({ course: "mongodb", class: "1", week: "w1", who: name }).toArray(function (err, doc) {
      console.log("开始查询教师上传")
      console.log(doc)
      res.render("teacherup", {
        teauplist: doc,
      });//跳转到页面并传值
    })
    db.close();
  });
});



router.get("/teauplist", function (req, res) {
  var name = req.session.user.name
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('teacherup');//连接表
    collection.find({ course: seld1, class: seld2, week: seld3, who: name }).toArray(function (err, doc) {
      console.log("teauplist choose seld1" + seld1 + seld2 + seld3)
      console.log("data:" + doc)
      res.render("teacherup", {
        teauplist: doc,
      });//跳转到class并传值，此处导致一个bug，跳转后下拉选择还是默认一班，不会变
    })
    db.close();
  });
});



router.get("/teauplist2", function (req, res) {
  var belong = req.session.user.belong
  var classs = req.session.user.class
  console.log("学生班级为" + classs)
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('teacherup');//连接表
    collection.find({ course: seld1, week: seld2, who: belong, class: classs }).toArray(function (err, doc) {
      console.log("teauplist choose seld1" + seld1 + seld2 + seld3)
      console.log("data:" + doc)
      res.render("student", {
        teauplist: doc,
      });//跳转到class并传值，此处导致一个bug，跳转后下拉选择还是默认一班，不会变
    })
    db.close();
  });
});



router.get("/myup", function (req, res) {
  var belong = req.session.user.belong
  var classs = req.session.user.class
  var name = req.session.user.name
  console.log("学生班级为" + classs)
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('teacherup');//连接表
    collection.find({ course: "mongodb", week: "w1", towho: belong }).toArray(function (err, doc) {
      res.render("myup", {
        myuplist: doc,
      });//跳转到class并传值，此处导致一个bug，跳转后下拉选择还是默认一班，不会变
    })
    db.close();
  });
});



router.get("/myuplist", function (req, res) {
  var belong = req.session.user.belong
  var classs = req.session.user.class
  var name = req.session.user.name
  console.log("学生班级为" + classs)
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('teacherup');//连接表
    collection.find({ course: seld1, week: seld3, who: name }).toArray(function (err, doc) {
      res.render("myup", {
        myuplist: doc,
      });//跳转到class并传值，此处导致一个bug，跳转后下拉选择还是默认一班，不会变
    })
    db.close();
  });
});




//文件上传
router.post('/file/uploading', function (req, res, next) {
  var form = new multiparty.Form({ uploadDir: './public/uploads/files/' });//获取前端表单数据
  form.parse(req, function (err, fields, files) {
    var filesTmp = JSON.stringify(files, null, 2);//解析
    var towho = req.session.user.belong
    var ccourse = fields.name[0];
    var cclass = fields.name[1];
    var cweek = fields.name[2];
    var cdate = fields.name[3];
    console.log("开始输出选择信息")
    console.log(ccourse + cclass + cweek + cdate)
    if (err) {
      console.log('parse error: ' + err);
    }
    else {
      console.log('parse files: ' + filesTmp);
      var inputFile = files.inputFile[0];//将inputFile定义为上传的文件
      var uploadedPath = inputFile.path;//定义原始路径
      var dstPath = './public/uploads/files/' + inputFile.originalFilename;//定义新路径，用以改名
      var uppath = './public/uploads/files/'
      fs.rename(uploadedPath, dstPath, function (err) {//重命名文件为原始名     ！！！缺省后文件名为随机
        if (err) {
          console.log('upload error: ' + err);
        } else {
          console.log('upload ok');
          console.log(ccourse);
          console.log(cclass);
          console.log(cweek);
          console.log(cdate);
          var upna = inputFile.originalFilename  //定义文件名用于存进数据库
          var upbywho = req.session.user.name;
          MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
            var collection = db.collection('teacherup');//连接表
            collection.insert({ url: uppath, name: upna, towho: towho, who: upbywho, course: ccourse, class: cclass, week: cweek, date: cdate }, function (err, result) {//写入
              if (err) {
                console.log("insert wrong")
              } else {
                console.log(result)
              }
            })
            db.close();
          });
        }
      });
    }
  });
  if (req.session.user.who == "teacher") {
    res.redirect('/teacher')//完成后跳转回teacher页面
  } else if (req.session.user.who == "student") {
    res.redirect('/student')
  }
});





//下载函数
router.post("/download/:stuId", function (req, res) {
  var stuId = req.params.stuId;
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    var collection = db.collection('teacherup');//连接表
    collection.findOne({ _id: ObjectID(stuId) }, function (err, doc) {//查找
      var url = doc.url
      var name = doc.name
      console.log(url + name)
      res.download(url + name)
    })
    db.close();
  });
})




//excel表上传
router.route("/excelup").get(function (req, res) {
  res.render("excelup")
})




//相应excel表上传
router.post("/excel/uploading", function (req, res) {
  var form = new multiparty.Form({ uploadDir: './public/uploads/' });//获取前端表单数据
  form.parse(req, function (err, fields, files) {
    var filesTmp = JSON.stringify(files, null, 2);
    if (err) {
      console.log('parse error: ' + err);
    } else {
      console.log('parse files: ' + filesTmp);
      var inputFile = files.inputFile[0];//将inputFile定义为上传的文件
      var uploadedPath = inputFile.path;//定义原始路径
      var dstPath = './public/uploads/excel/' + inputFile.originalFilename;//定义新路径，用以改名
      fs.rename(uploadedPath, dstPath, function (err) {//重命名文件为原始名     ！！！缺省后文件名为随机
        if (err) {
          console.log('upload error: ' + err);
        } else {
          console.log('upload ok');
          //将excel转成json
          node_xj = require("xls-to-json");
          node_xj({
            input: "./public/uploads/excel/demo.xls",//输入 excel表所在
            output: "./public/uploads/excel/output1.json"//输出  json所在
          }, function (err, result) {
            if (err) {
              console.error(err);
            } else {
              console.log("已转换");
            }
          });
        }
      });
    }
  });
  res.redirect('/we')//跳转
})




//解析json文件并导入数据库
router.route("/we").get(function (req, res) {
  console.log("going to we")
  var file = "./public/uploads/excel/output1.json";//获取json文件   
  var result = JSON.parse(fs.readFileSync(file));//储存解析后的数组
  console.log("已解析")
  console.log(result)
  MongoClient.connect('mongodb://localhost:27017/hw', function (err, db) {//连接数据库
    console.log("已连接数据库")
    var collection = db.collection('users');//连接表
    var jsonLength = 0;
    for (var item in result) {
      jsonLength++;
      console.log("开始读取json长度，当前长度为" + jsonLength);
    }//读取json文件长度
    console.log("开始遍历")
    for (var i = 0; i < jsonLength; i++) {
      //遍历json
      var data = {
        name: result[i].name,
        password: result[i].password,
        no: result[i].no,
        department: result[i].department,
        class: result[i].class,
        who: result[i].who,
        course: result[i].course,
        belong: result[i].belong
      }//定义字段
      collection.insert(data, function (err, result) {//写入数据库
        if (err) {
          console.log("insert wrong")
        } else {
          console.log("开始写入数据库")
        }
      })
    }
    db.close();
    console.log("已写入数据库并关闭数据库")
  }); if (req.session.user.who == "admin") {
    res.redirect('/admin')//跳转回class页面 
  } else if (req.session.user.who == "teacher") {
    res.redirect('/class')
  }
})









//上传页面
router.get("/test", function (req, res) {
  res.render("test");
});
router.get("/stuup", function (req, res) {
  res.render("stuup");
});


//注销
router.get("/logout", function (req, res) {
  console.log("out");
  req.session.user = null;
  req.session.error = null;
  res.redirect("/");
});





module.exports = router;